package com.sicpa.framework.web.service;

import com.sicpa.common.constant.Constants;
import com.sicpa.common.core.domain.AjaxResult;
import com.sicpa.common.core.domain.entity.AntiCounterfeitingRegisteredOffice;
import com.sicpa.common.core.domain.entity.SysRole;
import com.sicpa.common.core.domain.entity.SysUser;
import com.sicpa.common.core.domain.model.LoginUser;
import com.sicpa.common.core.redis.RedisCache;
import com.sicpa.common.enums.PerssionCheckEnum;
import com.sicpa.common.exception.CustomException;
import com.sicpa.common.exception.user.UserPasswordNotMatchException;
import com.sicpa.common.utils.MessageUtils;
import com.sicpa.common.utils.SecurityUtils;
import com.sicpa.framework.manager.AsyncManager;
import com.sicpa.framework.manager.factory.AsyncFactory;
import com.sicpa.system.mapper.*;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private AntiCounterfeitingRegisteredOfficeMapper antiCounterfeitingRegisteredOfficeMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 图片验证码
//        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//        String captcha = redisCache.getCacheObject(verifyKey);
//        redisCache.deleteObject(verifyKey);
//        if (captcha == null)
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
//            throw new CaptchaExpireException();
//        }
//        if (!code.equalsIgnoreCase(captcha))
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            throw new CaptchaException();
//        }

        SysUser sysuser = sysUserMapper.selectUserByUserName(username);
        if(sysuser == null){
            throw new UserPasswordNotMatchException();
        }
        Long officeId = sysuser.getOfficeId();
        //根据用户姓名为事务所编号去事务所查询是否为普通事务所账号
        AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.getDetailById(officeId);
        //为事务所账号,则判断是否为外省注册账号,账号为空,直接跳过
        if (!StringUtils.isEmpty(office) ) {
            if( office.getStatus() != 1){
                throw new UserPasswordNotMatchException();
            }
            if (!StringUtils.isEmpty(office.getIsForever()) && office.getIsRegister() == 1) {
                //为外省注册账号,判断是否为长期权限 0为临时权限
                if (!StringUtils.isEmpty(office.getIsForever()) && office.getIsForever() == 0) {

                    //临时权限,判断是否过期
                    LocalDate effectDate = office.getEffectTime();
                    if (effectDate.isBefore(LocalDate.now())) {
                        //过期则将其权限改为长期权限,先去角色分配中间表删除对应权限分配数据,再重新分配
                        antiCounterfeitingRegisteredOfficeMapper.deletePowersByOfficeId(office.getOfficeId());
                        SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(PerssionCheckEnum.OFFICE_LONG_TERM.getPerssionKey());
                        List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(sysRole.getRoleId());
                        antiCounterfeitingRegisteredOfficeMapper.batchOfficePowers(office.getOfficeId(), menuIds);

                    }
                }
            }
        }

        //用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                Object loginErrors = redisCache.getCacheObject(Constants.LOGIN_PWD_ERROR_COUNT + username);
                if(loginErrors==null){
                    redisCache.setCacheObject(Constants.LOGIN_PWD_ERROR_COUNT + username,1,2, TimeUnit.MINUTES);
                }else{
                    redisCache.setCacheObject(Constants.LOGIN_PWD_ERROR_COUNT + username, NumberUtils.toInt(loginErrors.toString())+1);
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
